from farstyle.filters import FilterBase
from farstyle import settings

import os
import subprocess
import tempfile

binary = getattr(settings, 'SASS_BINARY')

class SASSFilter(FilterBase):
    def filter_css(self, css):
        tmp, tmp_name = tempfile.mkstemp()
        os.close(tmp)
        process = subprocess.Popen([binary,
            '--stdin',
            '--trace',
            '--style', settings.DEBUG and 'nested' or 'compressed',
            '--no-cache',
            tmp_name
        ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdoutdata, stderrdata = process.communicate(css.encode('utf-8'))

        if stderrdata:
            if settings.DEBUG:
                os.unlink(tmp_name)
                raise ValueError, stderrdata
            filtered_css = u''
        else:
            f = open(tmp_name, 'r')
            filtered_css = f.read()
            f.close()

        os.unlink(tmp_name)
        return filtered_css
